<template>
  <div>
    <div>
      <el-button @click="handleAddClick()" type="primary" size="small">添加角色</el-button>
    </div>
    <el-table :data="roleList" v-loading="loading" style="width: 100%">
      <el-table-column prop="role" label="角色字符串" width="180"></el-table-column>
      <el-table-column prop="roleName" label="角色描述" min-width="180"></el-table-column>
      <el-table-column fixed="right" label="操作" width="300">
        <template slot-scope="scope">
          <el-button type="primary" @click="handleEditClick(scope.row)" size="small" plain>菜单</el-button>
          <el-button type="primary" @click="handPermissionEditClick(scope.row)" size="small" plain>权限</el-button>
          <el-button type="primary" @click="handleEditClick(scope.row)" size="small" plain>编辑</el-button>
          <el-button type="danger" @click="handleRemoveClick(scope.row)" size="small" plain>删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <br>
    <el-pagination background layout="prev, pager, next" :total="pageInfo.total"></el-pagination>
    <el-dialog :title="!editing?'新建角色':'编辑角色'" :visible.sync="showEditDialog">
      <el-form ref="roleEditForm" :model="editRole" :rules="editRoleRules">
        <el-form-item label="角色字符串" :label-width="formLabelWidth" prop="role">
          <div class="text-input">
            <el-input v-model="editRole.role" auto-complete="off"></el-input>
          </div>
        </el-form-item>
        <el-form-item label="角色描述" :label-width="formLabelWidth" prop="roleName">
          <div class="text-input">
            <el-input v-model="editRole.roleName" auto-complete="off"></el-input>
          </div>
        </el-form-item>
        <el-form-item label="菜单" :label-width="formLabelWidth" prop="menus">
          <el-tree node-key="id" ref="tree"
            :data="treeData"
            show-checkbox
            @check="menuCheckBoxClick"
            :expand-on-click-node="false"
            default-expand-all>
          </el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showEditDialog = false">取 消</el-button>
        <el-button type="primary" @click="dialogConfirm()">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="编辑权限" :visible.sync="permissionEditDialog">
      <div style="text-align: center;">
        <el-transfer v-model="checkedPermissionList" style="text-align: left; display: inline-block"
          :data="actionList"
          :titles="['未有权限', '已有权限']"
          :props="permissionProps">
        </el-transfer>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="permissionEditDialog = false">取 消</el-button>
        <el-button type="primary" @click="permissionEditConfirmClick()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    return {
      roleList: [],
      loading: false,
      menuList: [],
      treeData: [],
      actionList: [],
      checkedPermissionList: [],
      total: '',
      pageInfo: {
        page: 0,
        pageSize: 0,
        total: 0
      },
      permissionProps: {
        key: 'id',
        label: 'permissionName'
      },
      showEditDialog: false,
      permissionEditDialog: false,
      editing: true,
      formLabelWidth: '100px',
      editRole: {
        id: null,
        role: '',
        menus: [],
        roleName: ''
      },
      editRoleRules: {
        menus: [{ type: 'array', required: true, message: '请至少选择一项菜单', trigger: 'change' }],
        role: [
          { required: true, message: '请输入角色字符串', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        roleName: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 2, max: 12, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    reloadRoleList: function () {
      this.loading = true
      var postData = { page: this.pageInfo.page, pageSize: this.$config.PAGE_SIZE }
      this.$axios.post(this.$api.ROLE_PAGE.url, postData).then(response => {
        if (response.data.code === 0) {
          // 登录成功设置
          this.loading = false
          this.roleList = response.data.data.pageData
          this.pageInfo.total = response.data.data.total
        }
      })
    },
    reloadMenuList: function () {
      this.loading = true
      var postData = {}
      this.$axios.post(this.$api.MENU_ALL.url, postData).then(response => {
        if (response.data.code === 0) {
          // 登录成功设置
          this.loading = false
          this.menuList = response.data.data.pageData.sort((x, y) => { return x.sort < y.sort })
          this.total = response.data.data.total
          console.log('response.data.data:', this.total, response.data.data)
          console.log('菜单:', this.total, this.menuList)
          this.genTree()
        }
      })
    },
    reloadActionList: function () {
      this.loading = true
      this.$axios.get(this.$api.ACTION_ALL.url).then(response => {
        if (response.data.code === 0) {
          this.loading = false
          this.actionList = response.data.data.all
          console.log('actionList', this.actionList)
        }
      })
    },
    genTree: function () {
      var tree = [{ id: 0, label: '根节点', children: [] }]
      for (var i in this.menuList) {
        var menu = this.menuList[i]
        if (menu.parent === null) {
          var node = { id: menu.id, label: menu.name, children: [] }
          var children = this.menuList.filter((x) => {
            if (x.parent === null) {
              return false
            }
            return menu.id === x.parent.id
          })
          children.forEach((x) => {
            node.children.push({ id: x.id, label: x.name })
          })
          console.log('children', node.children)
          tree[0].children.push(node)
        }
      }
      this.treeData = tree[0].children
      console.log('treeData', this.treeData)
    },
    clearEditRoleForm: function () {
      this.editRole.id = null
      this.editRole.role = ''
      this.editRole.roleName = ''
      this.$nextTick(() => {
        this.$refs.tree.setCheckedKeys([])
      })
      if (this.$refs.roleEditForm) {
        this.$refs.roleEditForm.resetFields()
      }
    },
    menuCheckBoxClick: function (data, self) {
      this.editRole.menus = self.checkedKeys
    },
    handleAddClick: function () {
      this.editing = false
      this.clearEditRoleForm()
      this.showEditDialog = true
    },
    handPermissionEditClick: function (role) {
      this.editing = true
      this.editRole.id = role.id
      this.checkedPermissionList = role.actionSet.map(action => action.id)
      this.permissionEditDialog = true
    },
    handleEditClick: function (role) {
      this.editing = true
      this.clearEditRoleForm()
      this.editRole.id = role.id
      this.editRole.role = role.role
      this.editRole.roleName = role.roleName
      this.$nextTick(() => {
        this.editRole.menus = role.menuSet
        role.menuSet.forEach(menu => {
          this.$refs.tree.setChecked(menu.id, true, false)
        })
      })
      // 打开
      this.showEditDialog = true
    },
    handleRemoveClick: function (role) {
      var _this = this
      this.$bus.$emit('showYesNo', '系统信息', '您要删除该角色吗？', function () {
        var postData = { id: role.id }
        this.$axios.post(this.$api.ROLE_REMOVE.url, postData).then(response => {
          console.log('respone', response)
          if (response.data.code === 0) {
            this.$message({
              message: '操作成功!',
              type: 'success'
            })
            _this.reloadRoleList()
          }
        })
      })
    },
    dialogConfirm: function () {
      this.$refs['roleEditForm'].validate((valid) => {
        if (valid) {
          var url = this.editing ? this.$api.ROLE_UPDATE.url : this.$api.ROLE_ADD.url
          var checkedKeys = this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys())
          var menus = checkedKeys.map(key => { return { id: key } })
          var postData = {
            id: this.editing ? this.editRole.id : null,
            role: this.editRole.role,
            roleName: this.editRole.roleName,
            menuSet: menus
          }
          console.log(url, postData)
          this.$axios.post(url, postData).then(response => {
            if (response.data.code === 0) {
              // 登录成功设置
              this.loading = false
              this.$message({
                message: '操作成功!',
                type: 'success'
              })
              this.showEditDialog = false
              this.clearEditRoleForm()
              this.reloadRoleList()
            }
          }).catch((err) => {
            this.logining = false
            this.$message.error(err.message)
          })
        }
      })
    },
    permissionEditConfirmClick () {
      var url = this.$api.ROLE_UPDATE_ACTION.url
      var permissions = this.checkedPermissionList.map(key => { return { id: key } })
      var postData = {
        id: this.editing ? this.editRole.id : null,
        actionSet: permissions
      }
      console.log(url, postData)
      this.$axios.post(url, postData).then(response => {
        if (response.data.code === 0) {
          // 登录成功设置
          this.loading = false
          this.$message({
            message: '操作成功!',
            type: 'success'
          })
          this.permissionEditDialog = false
          this.reloadRoleList()
        }
      }).catch((err) => {
        this.logining = false
        this.$message.error(err.message)
      })
    }
  },
  mounted: function () {
    this.reloadRoleList()
    this.reloadMenuList()
    this.reloadActionList()
  }
}
</script>
<style scoped>
.text-input{
  width:240px;
}
</style>
